package com.sunny.feign.cloud;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.sunny.feign.custom.CustomHystrix;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author Sunny
 * @date 2020/2/24
 */
@RestController
public class CustomHystrixController {

    @GetMapping("hystrix/say")
    @HystrixCommand(fallbackMethod = "errorSay",
    //设置超时时间为10ms
    commandProperties = {@HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "10")})
    public String hystrixSay(String msg) throws InterruptedException {
        int timeout = ThreadLocalRandom.current().nextInt(20);
        System.out.println("sleep " + timeout + " ms");
        TimeUnit.MILLISECONDS.sleep(timeout);
        return "Hello " + msg;
    }

    @GetMapping("custom/say")
    @CustomHystrix(timeout = 10, semaphore = 1)
    public String customSay(String msg) throws InterruptedException {
        int timeout = ThreadLocalRandom.current().nextInt(20);
        System.out.println("sleep " + timeout + " ms");
        TimeUnit.MILLISECONDS.sleep(timeout);
        return "Hello customSay " + msg;
    }

    public String errorSay(String msg) {
        return "Error say " + msg;
    }
}
